/**
 * Created by chengming on 18/5/27.
 * version 1.0
 */
const BaseJsonAdapter = require('../base/BaseJsonAdapter');
const iconv = require("iconv-lite");
const vm = require('vm');
const request = require('request-promise');
const logger = require('../../conf/logger');
const querystring = require("querystring")
const urlencode = require("urlencode")
const urlTool = require('url');

/**
 * Cheddar
 * @type {module.Bjp2p}
 */
module.exports = class CheddarJson extends BaseJsonAdapter {


    async doRequest() {
        var form = {
            "query": "query LatestQuery(  $sort: SortInput  $count: Int!  $cursor: String) {  ...LatestList_videos}fragment LatestList_videos on Query {  videos(include_unpublished: false, include_private: false, clip: true, first: $count, after: $cursor, sort: $sort) {    edges {      node {        id        ...StandardListCard_video        __typename      }      cursor    }    pageInfo {      endCursor      hasNextPage    }  }}fragment StandardListCard_video on Video {  ...Thumbnail_video  ...StandardTextCard_video  slug  db_id}fragment Thumbnail_video on Video {  sd_thumbnails: thumbnails(aspect_ratio: SD) {    small    medium    large  }  hd_thumbnails: thumbnails(aspect_ratio: HD) {    small    medium    large  }  film_thumbnails: thumbnails(aspect_ratio: FILM) {    small    medium    large  }  square_thumbnails: thumbnails(aspect_ratio: SQUARE) {    small    medium    large  }}fragment StandardTextCard_video on Video {  aired_at  updated_at  title  description}",
            "variables": {
                "sort": {
                    "attribute": "aired_at",
                    "direction": "DESC"
                },
                "count": 10,
                "cursor": null
            }
        }


        let auth = this.requestHeaders.Authorization;
        var options = {
            headers:{
                'Content-Type':'application/json; charset=UTF-8',
                'Authorization':auth
            },
            method:'POST',
            uri:this.requestUrl,
            body:form,
            json:true
        }
        let body = await request(options)
        return body;
    }


    async reqJson() {
        const body = await this.doRequest();
        // let decodeBody = iconv.decode(body, this.encoding).toString();
        // decodeBody = urlencode.decode(decodeBody,this.encoding);
        // let data = JSON.parse(decodeBody);
        // console.log("-----decodeBody: " + decodeBody)
        return body;
    }

    async execute() {
        logger.debug('开始执行抓取->' + this.pageName);

        let selectedBody = await this.reqJson();

        let decodeBody = selectedBody;

        logger.debug("-------------------------" + this.pageName + "的请求结果body为:" + JSON.stringify(selectedBody));

        logger.debug(this.pageTitle + '抓取执行完毕,开始分析文本');
        if (this.linkRule.length == 0) {
            logger.warn(this.pageName + '没有json内容规则');
            if (!this.isTest) {
                await report(this.pageSite, this.pageTitle, '', '没有json内容规则');
            }
            return {
                code: 401,
                errMsg: '没有json内容规则'
            };
        }

        let [jsonArr, jsonTitle, jsonHref] = this.linkRule.split('#');

        if (jsonArr.length == 0) {
            logger.warn(this.pageName + 'json数组属性不存在');
            if (!this.isTest) {
                await report(this.pageSite, this.pageTitle, '', 'json数组属性不存在');
            }
            return {
                code: 402,
                errMsg: 'json数组属性不存在'
            }
        }

        let props = jsonArr.split('.');
        logger.debug(this.pageName + "使用以下属性取出数组对象" + JSON.stringify(props));


        let propLen = props.length;
        for (let i = 0; i < propLen; i++) {
            selectedBody = selectedBody[props[i]];
            if (i != propLen - 1 && selectedBody instanceof Array) {
                //如果属性中为数组,则默认取出第一个元素
                selectedBody = selectedBody[0];
            }
            if (!selectedBody) {
                logger.error(this.pageName + "对象中没有" + props[i] + "属性");
                if (!this.isTest) {
                    await report(this.pageSite, this.pageTitle, '', "对象中没有" + props[i] + "属性");
                }
                return {
                    code: 403,
                    errMsg: "对象中没有" + props[i] + "属性"
                }
            }
        }

        let contents = [];
        let that = this;
        let rangeText = '';

        for (let item of selectedBody) {
            let title = item['node'][jsonTitle];
            let href = 'https://cheddar.com/videos/' + item['node'][jsonHref];
            contents.push({
                title: title,
                href: href
            });
            rangeText += title + href;
        }
        ;

        if (rangeText.length == 0) {
            logger.warn(this.pageName + "->" + this.linkRule + "此抓取规则下,无内容匹配");
            if (!this.isTest) {
                await report(this.pageSite, this.pageTitle, '', this.linkRule + "此抓取规则下,无内容匹配 " + selectedBody);
            }
            return {
                code: 406,
                errMsg: this.linkRule + "此抓取规则下,无内容匹配 " + selectedBody
            }
        }

        await super.postSocket(this.id, this.rangeMd5, rangeText, contents,  decodeBody, this.cates, this.pageTitle, this.sourceTime, this.channel,
            this.followLink, this.foreign, this.contentRule, this.linkUniqueBy);


        return await this.postFilterUnique(contents,
            this.cates,
            this.foreign,
            this.linkUniqueBy,
            this.followLink,
            this.sourceTime,
            this.pageTitle,
            this.titleRule,
            this.contentRule,
            this.channel);
    }
}
